export class Queue {
    constructor() {
        this.items = []
    }

    // 向队列尾部添加项
    enqueue(element) {
        this.items.push(element)
    }

    // 移除队列首部元素
    dequeue() {
        return this.items.shift()
    }

    // 查看第一个元素(第一个被添加, 同时第一个被移除)
    front() {
        if (this.items.length === 0) {
            return null
        }
        return this.items[0]
    }

    isEmpty() {
        return this.items.length === 0
    }

    size() {
        return this.items.length
    }
}

// 优先级队列开始
class QueueElement {
    constructor(element, priority) {
        this.element = element
        this.priority = priority
    }
}

export class PriorityQueue extends Queue {
    enqueue(element, priority) {
        // 1. 创建QueueElement对象
        const queueElement = new QueueElement(element, priority)
        // 2. 考虑如何插入
        if (this.isEmpty()) {
            this.items.push(queueElement)
        } else {
            let added = false
            for (let i = 0; i < this.size(); i++) {
                // 数字越小优先级越高, 队列从小到大
                if (this.items[i].priority > queueElement.priority) {
                    this.items.splice(i, 0, queueElement)
                    added = true
                    break
                }
            }
            // 如果没有找到, 说明优先级最低, 插入队尾
            if (!added) {
                this.items.push(queueElement)
            }
        }
    }
}